package com.yf.customdubbo.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

public class ZkServiceRegistryCenterImpl implements IServiceRegistryCenter {

    /**
     * Curator实现对zk的操作
     */
    private CuratorFramework curatorFramework;
    public ZkServiceRegistryCenterImpl(){
        curatorFramework= CuratorFrameworkFactory.builder().connectString(ZkConfig.zkAddress)
                .sessionTimeoutMs(4000).retryPolicy(new ExponentialBackoffRetry(1000,10)).build();
        //客户端已经连接上zk服务端了
        curatorFramework.start();
    }

    @Override
    public void register(String serviceName, String serviceAddress) {
        String servicePath=ZkConfig.zkRegistryPath+"/"+serviceName;
        //判断这个节点是否存在，不存在则创建

        try{
            if(curatorFramework.checkExists().forPath(servicePath)==null){
                curatorFramework.create().creatingParentsIfNeeded().
                        withMode(CreateMode.PERSISTENT).forPath(servicePath,"0".getBytes());
            }
            System.out.println("serviceName创建成功"+servicePath);

            //在servicePath下创建临时节点，表示调用的地址
            //  /registrys/com.xxx.xxService/127.0.0.1 临时节点:服务停止，则自动删除了（临时节点的特性）
            String addressPath=servicePath+"/"+serviceAddress;
            String addNode=curatorFramework.create().withMode(CreateMode.EPHEMERAL)
                    .forPath(addressPath,"0".getBytes());

            System.out.println("serviceAddress创建成功："+addNode);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
